/*
 * @Author: jqgao2
 * @Date: 2022-11-17 14:14:49
 * @LastEditTime: 2022-11-17 14:31:41
 * @Description: 通用工具
 * @FilePath: \cucc-front\src\utils\commom.ts
 * @LastEditors: jqgao2
 */

/**
 * 设置一个带当前时间的localStorage
 *
 *   */
export const setStorage = (key: string, value: string) => {
  // 获取当前时间戳
  const now = new Date().getTime();
  localStorage.setItem(
    key,
    JSON.stringify({
      time: now,
      data: value,
    })
  );
};

/**
 * 获取带过期时间的localStorage
 *
 * exp 过期时间，单位  ms
 *
 *   */
export const getStorage = (key: string, exp: number) => {
  let data = localStorage.getItem(key);

  if (!data) {
    return null;
  }

  const now = new Date().getTime();
  if (now - JSON.parse(data).time > exp) {
    localStorage.removeItem(key);
    return null;
  }

  return JSON.parse(data).data;
};
